﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InformationSystem.BLL.Core.Service;
using InformationSystem.BLL.Core.Model;
using System.Text;

namespace InformationSystem.WebSite.Forum
{
    public partial class ForumList : BasePage
    {
        public IForumService ForumService { get; set; }
        protected LoginUser user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = base.LoginUser;
            lastlogintime.InnerText = string.Format("最后登录时间:{0}", user.LastLoginDateTime.ToString("yyyy/MM/dd HH:mm"));
            int forumid = 0;
            int tabid = 0;
            int reuqestpage = 1;
            if (Request.QueryString["forumid"] != null)
            {
                int.TryParse(Request.QueryString["forumid"], out forumid);
            }
            if (Request.QueryString["tabid"] != null)
            {
                int.TryParse(Request.QueryString["tabid"], out tabid);
            }
            if (Request.QueryString["page"] != null)
            {
                int.TryParse(Request.QueryString["page"], out reuqestpage);
            }
            //如果没有有效ID转入默认学院主页
            if (forumid == 0) forumid = base.LoginUser.CollegeID;
            College college = ForumService.GetCollegeForumInfo(forumid, base.LoginUser);
            if (college == null) return;
            if (!college.CurrentUserCanVisitForum)
            {
                return;
            }
            //this.CreateTable(college, tabid);
            this.ReadForum(college, forumid, tabid, reuqestpage);
        }

        private void ReadForum(College college, int forumid, int currentTabid, int requestpage)
        {
            int allrecordscount = 0;
            int pagerecord = (int)Application[Common.ForumPageRecordCount];
            //动态生成标签页
            bool result = this.CreateTable(college, currentTabid);
            IList<ThreadInfo> tlist = ForumService.GetThreads(college.CollegeId, result ? currentTabid : 0, pagerecord, requestpage, out allrecordscount);
            int pagesneed = allrecordscount / pagerecord + (allrecordscount % pagerecord == 0 ? 0 : 1);
            if (requestpage > pagesneed) requestpage = pagesneed;
            //生成分页链接
            this.RenderPageNo(requestpage, allrecordscount, forumid, currentTabid);
            //生成实际数据
            this.RendPageContent(tlist, requestpage, currentTabid);
        }

        private string RenderStickthread(ThreadInfo info, int requestpage, int currentTabid)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<tbody id=\"stickthread_{0}\">", info.ThreadID);
            builder.Append("<tr>");
            builder.AppendFormat("<td class=\"icn\"><a title=\"全局置顶主题 - 新窗口打开\" href=\"ForumContent.aspx?threadid={0}&fp={1}&tabid={2}\" target=\"_blank\"><img alt=\"全局置顶\" src=\"image/pin_3.gif\"></a></td>", info.ThreadID, requestpage, currentTabid);
            builder.AppendFormat("<th class=\"common\"><em>[<a href=\"ForumList.aspx?tabid={0}\">{1}</a>]</em><a style=\"color: #ee1b2e; font-weight: bold\" class=\"xst\" href=\"ForumContent.aspx?threadid={2}&fp={3}&tabid={4}\">{5}</a></th>", info.ThreadType, info.ThreadTypeName, info.ThreadID, requestpage, currentTabid, info.ThreadSubject);
            builder.AppendFormat("<td class=\"by\"><cite>{0}</cite> <em><span>{1}</span></em></td>", (info.HideName && info.CreatUserID != LoginUser.UserID) ? Common.Anonymous : info.CreatUserName, info.CreateTime);
            builder.AppendFormat("<td class=\"num\">{0}<em>{1}</em></td>", info.ReplyCount, info.VisitedCount);
            builder.AppendFormat("<td class=\"by\"><cite>{0}</cite><em> <span title=\"{1}\">{1}</span></em></td>", (info.LastReplyHideName && info.LastReplyUserID != LoginUser.UserID) ? Common.Anonymous : info.LastReplyUserName, info.LastReplyTime);
            builder.Append("</tr>");
            builder.Append("</tbody>");
            return builder.ToString();
        }

        private string Renderseparatorline()
        {
            return "<tbody id=\"separatorline\"><tr class=\"ts\"> <td>&nbsp;</td><th>版块主题</th> <td> &nbsp;</td> <td> &nbsp;</td><td>&nbsp;</td></tr></tbody>";
        }

        private string RenderNormalthread(ThreadInfo info, int requestpage, int currentTabid)
        {

            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<tbody id=\"normalthread_{0}\">", info.ThreadID);
            builder.Append("<tr>");
            builder.AppendFormat("<td class=\"icn\"><a title=\"新窗口打开\" href=\"ForumContent.aspx?threadid={0}&fp={1}&tabid={2}\" target=\"_blank\"><img alt=\"全局置顶\" src=\"image/folder_new.gif\"></a></td>", info.ThreadID, requestpage, currentTabid);
            builder.AppendFormat("<th class=\"new\"><em>[<a href=\"ForumList.aspx?tabid={0}\">{1}</a>]</em><a  class=\"xst\" href=\"ForumContent.aspx?threadid={2}&fp={3}&tabid={4}\">{5}</a></th>", info.ThreadType, info.ThreadTypeName, info.ThreadID, requestpage,currentTabid, info.ThreadSubject);
            builder.AppendFormat("<td class=\"by\"><cite>{0}</cite> <em><span>{1}</span></em></td>", (info.HideName && info.CreatUserID != LoginUser.UserID) ? Common.Anonymous : info.CreatUserName, info.CreateTime);
            builder.AppendFormat("<td class=\"num\">{0}<em>{1}</em></td>", info.ReplyCount, info.VisitedCount);
            builder.AppendFormat("<td class=\"by\"><cite>{0}</cite><em> <span title=\"{1}\">{1}</span></em></td>", (info.LastReplyHideName && info.LastReplyUserID != LoginUser.UserID) ? Common.Anonymous : info.LastReplyUserName, info.LastReplyTime);
            builder.Append("</tr>");
            builder.Append("</tbody>");
            return builder.ToString();
        }

        private void RendPageContent(IList<ThreadInfo> tlist, int requestpage, int currentTabid)
        {

            if (tlist == null || tlist.Count == 0) return;
            bool isOnTopFirst = false;
            StringBuilder builder = new StringBuilder();
            builder.Append("<table cellspacing=\"0\"  cellpadding=\"0\">");
            for (int i = 0; i < tlist.Count; i++)
            {
                if (i == 0)
                {
                    if (tlist[i].IsOnTop) isOnTopFirst = true;
                }
                if (tlist[i].IsOnTop)
                {
                    builder.Append(this.RenderStickthread(tlist[i], requestpage, currentTabid));
                }
                else
                {
                    if (isOnTopFirst)
                    {
                        //draw sep
                        builder.Append(this.Renderseparatorline());
                        isOnTopFirst = false;
                    }
                    //draw common thread
                    builder.Append(this.RenderNormalthread(tlist[i], requestpage,currentTabid));
                }
            }
            builder.Append("</table>");
            subjectlistcon.InnerHtml = builder.ToString();
        }
        private void RenderPageNo(int requestpage, int allrecordscount, int forumid, int currentTabid)
        {
            int pagerecord = (int)Application[Common.ForumPageRecordCount];
            //分页规则
            /*
             小于一页不限时分页标签
             * 含首页和尾页最多显示10页
             * 10页以及之内不显示第一页和尾页
             * 当前页为前5页不隐藏前面的页
             * 当前页最最后5页时不隐藏后面页
             * 其余情况 第一页  --当前页 ++最后一页
             */
            //<strong>1</strong>当前选中页
            //<a href="http://www.discuz.net/forum-26-2.html">2</a>其他页
            /*<label><input type="text" name="custompage" class="px" size="2" title="输入页码，按回车快速跳转" value="1"
                                    onkeydown="if(event.keyCode==13) {window.location='forum.php?mod=forumdisplay&fid=26&amp;page='+this.value; doane(event);}" /><span
                                        title="共 500 页"> / 500 页</span></label>*/
            //快速翻页
            //pgtop
            //显示当前 页的前 4页后4页，还有就用1 和最后一页显示
            int pagesneed = allrecordscount / pagerecord + (allrecordscount % pagerecord == 0 ? 0 : 1);
            StringBuilder innerhtml = new StringBuilder();
            if (pagesneed < 11)
            {
                for (int i = 1; i < pagesneed + 1; i++)
                {
                    if (requestpage == i)
                    {
                        innerhtml.AppendFormat("<strong>{0}</strong>", i);
                    }
                    else
                    {
                        innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                    }
                }
            }
            else
            {
                if (requestpage < 6)
                {
                    for (int i = 1; i < 6; i++)
                    {
                        if (requestpage == i)
                        {
                            innerhtml.AppendFormat("<strong>{0}</strong>", i);
                        }
                        else
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                        }
                    }

                    if (pagesneed - 5 < 5)
                    {
                        for (int i = 6; i < pagesneed + 1; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                        }
                    }
                    else
                    {
                        for (int i = 6; i < 10; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                        }
                        innerhtml.AppendFormat("<a href='{0}'>...{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), pagesneed), pagesneed);
                    }
                }
                if (requestpage > 5)
                {
                    innerhtml.AppendFormat("<a href='{0}'>1...</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), 1));
                    for (int i = requestpage - 3; i < requestpage; i++)
                    {
                        innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                    }
                    innerhtml.AppendFormat("<strong>{0}</strong>", requestpage);

                    if (pagesneed - requestpage < 5)
                    {
                        for (int i = requestpage + 1; i < pagesneed + 1; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                        }
                    }
                    else
                    {
                        for (int i = requestpage + 1; i < requestpage + 4; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), i), i);
                        }
                        innerhtml.AppendFormat("<a href='{0}'>...{1}</a>", string.Format("ForumList.aspx?forumid={0}{1}&page={2}", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), pagesneed), pagesneed);
                    }
                }
                innerhtml.AppendFormat("<label><input type='text' name='custompage' class='px' size='2' title='输入页码，按回车快速跳转' value='1' onkeydown=\"if(event.keyCode==13) {0}window.location='ForumList?forumid={1}{2}&page='+this.value; {3}\" /><span title='共 {4} 页'> / {4} 页</span></label>", "{", forumid, currentTabid == 0 ? "" : ("&tabid=" + currentTabid.ToString()), "}", pagesneed);
            }
            pgtop.InnerHtml = innerhtml.ToString();
            pgbottom.InnerHtml = innerhtml.ToString();
        }
        private bool CreateTable(College college, int currentTabid)
        {
            StringBuilder builder = new StringBuilder();
            bool isColorDraw = false;
            if (college.ThreadTypeList != null)
            {
                foreach (var item in college.ThreadTypeList)
                {
                    if (item.TypeID == currentTabid)
                    {
                        isColorDraw = true;
                    }
                    builder.AppendFormat("<li {0}><a href='{1}'>{2}</a></li>", item.TypeID == currentTabid ? "class='xw1 a'" : "", ("ForumList.aspx?forumid=" + college.CollegeId.ToString() + "&tabid=" + item.TypeID.ToString()), item.TypeName);
                }
            }
            builder.Insert(0, string.Format("<li id='ttp_all' {0}><a href='{1}'>全部</a></li>", isColorDraw ? "" : "class='xw1 a'", ("ForumList.aspx?forumid=" + college.CollegeId.ToString())));
            //<li id="ttp_all" class="xw1 a"><a id="all" runat="server">全部</a></li>
            //<li><a href=""><font color="green"><b>学习</b></font></a></li>
            thread_types.InnerHtml = builder.ToString();
            newspecial.HRef = "NewThread.aspx?forumid=" + college.CollegeId.ToString();
            newspecialbottom.HRef = "NewThread.aspx?forumid=" + college.CollegeId.ToString();
            return isColorDraw;
        }
        protected override bool CommitPermissionCheck()
        {
            throw new NotImplementedException();
        }
    }
}